﻿using AJWPFAdmin.Core.GlobalEvents;
using AJWPFAdmin.Core.HardwareSDKS;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Modules.Common.Views;
using AJWPFAdmin.Modules.Main.Views;
using AJWPFAdmin.Services;
using AJWPFAdmin.Services.AppointAPI;
using Microsoft.AspNetCore.Mvc;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Threading;

namespace AJWPFAdmin.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        private string _title = "门禁系统-岗亭端";
        public string Title
        {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }

        private string _apiDesc ;
        public string APIDesc
        {
            get { return _apiDesc; }
            set { SetProperty(ref _apiDesc, value); }
        }

        private string _ip;
        public string IP
        {
            get { return _ip; }
            set { SetProperty(ref _ip, value); }
        }

        private bool _menuOpen;
        public bool MenuOpen
        {
            get { return _menuOpen; }
            set { SetProperty(ref _menuOpen, value); }
        }

        private SystemUser _curUser;
        public SystemUser CurrentUser
        {
            get { return _curUser; }
            set { SetProperty(ref _curUser, value); }
        }

        private DateTime? _trialExpireDate;
        public DateTime? TrialExpireDate
        {
            get { return _trialExpireDate; }
            set { SetProperty(ref _trialExpireDate, value); }
        }

        private string _trialExpireDateText;
        public string TrialExpireDateText
        {
            get { return _trialExpireDateText; }
            set { SetProperty(ref _trialExpireDateText, value); }
        }

        private bool _isAuthorized;
        public bool IsAuthorized
        {
            get => _isAuthorized;
            set => SetProperty(ref _isAuthorized, value);
        }

        private DelegateCommand _openDataVerificationUploadDialogCmd;
        public DelegateCommand OpenDataVerificationUploadDialogCmd =>
            _openDataVerificationUploadDialogCmd ?? (_openDataVerificationUploadDialogCmd = new DelegateCommand(ExecuteOpenDataVerificationUploadDialogCmd));

        void ExecuteOpenDataVerificationUploadDialogCmd()
        {
            _dialogSvc.ShowDialog(nameof(DataVerificationUploadForm), r =>
            {

            });
        }

        private DelegateCommand _openManageMeasureListDialogCmd;
        public DelegateCommand OpenManageMeasureListDialogCmd =>
            _openManageMeasureListDialogCmd ?? (_openManageMeasureListDialogCmd = new DelegateCommand(ExecuteOpenManageMeasureListDialogCmd));

        void ExecuteOpenManageMeasureListDialogCmd()
        {
            _dialogSvc.ShowDialog(nameof(ManageMeasureList), r =>
            {

            });
        }

        private DelegateCommand _openAuthorizeDialogCmd;
        public DelegateCommand OpenAuthorizeDialogCmd =>
            _openAuthorizeDialogCmd ?? (_openAuthorizeDialogCmd = new DelegateCommand(ExecuteOpenAuthorizeDialogCmd));

        void ExecuteOpenAuthorizeDialogCmd()
        {
            _dialogSvc.ShowDialog(nameof(AuthorizeDialog), r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    IsAuthorized = true;
                    TrialExpireDate = null;
                    StopTimer();
                }
            });
        }

        private SideMenuNavEvent _sideMenuNavEvent;
        private IDialogService _dialogSvc;
        private AJConfigService _cfgSvc;
        private AppointAPISvc _appointAPISvc;
        private DispatcherTimer _dispatcherTimer;

        public MainWindowViewModel(IEventAggregator eventAggregator,
            AJConfigService cfgSvc,
            AppointAPISvc appointAPISvc,
            IDialogService dialogSvc,
            SystemUserService sysUserSvc)
        {
            IsAuthorized = true;
            _appointAPISvc = appointAPISvc;
            _curUser = sysUserSvc.CurrentUser;
            _cfgSvc = cfgSvc;
            _dialogSvc = dialogSvc;

            var version = Application.ResourceAssembly.GetName().Version;
            Title = $"清洁运输台账-岗亭端 {version}";

            APIDesc = appointAPISvc.API.KeyDescription;
            IP = CommonUtil.GetLocalIPV4();

            eventAggregator.GetEvent<ApplicationExitEvent>().Subscribe(() =>
            {
                StopTimer();

            });

            Task.Run(async () =>
            {
                var result = await _cfgSvc.TryActiveAsync(tryLocally: true, autoMode: true);

                TrialExpireDate = _cfgSvc.TrialConfigInfo == null ? null : _cfgSvc.TrialConfigInfo.ExpireDate;

                IsAuthorized = result.Success;

                if (TrialExpireDate.HasValue && DateTime.Now < TrialExpireDate)
                {
                    CheckExpireDate();
                }
            });

            // 开一个定时器检测试用时间
            _dispatcherTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMinutes(1),
            };
            _dispatcherTimer.Tick += (_, __) =>
            {
                CheckExpireDate();
            };
            _dispatcherTimer.Start();

        }

        private void StopTimer()
        {
            if (_dispatcherTimer?.IsEnabled == true)
            {
                _dispatcherTimer.Stop();
            }
        }

        private void CheckExpireDate()
        {
            var now = DateTime.Now;

            if (now < TrialExpireDate)
            {
                var span = TrialExpireDate.GetValueOrDefault().Subtract(now);
                TrialExpireDateText = $"{span.Days}天{span.Hours}小时{span.Minutes}分钟";
            }
            else if (now >= TrialExpireDate)
            {
                _dispatcherTimer.Stop();
                TrialExpireDate = null;
                TrialExpireDateText = "已到期";
                _cfgSvc.IsAuthorized = IsAuthorized = false;
            }
        }
    }

    public class TrialExpireDateConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var type = parameter?.ToString() ?? "text";

            if (value == null)
            {
                return type == "text" ? string.Empty : Visibility.Collapsed;
            }
            var date = (value as DateTime?).GetValueOrDefault();

            var span = date.Subtract(DateTime.Now);
            var days = System.Convert.ToInt32(span.TotalDays);
            return type == "text" ? (days > 0 ? $"{span.Days}天{span.Hours}小时{span.Minutes}分钟{span.Seconds}" : "已到期") : Visibility.Visible;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}
